<?php

namespace app\api\controller\exam;

use app\admin\model\exam\MainCateModel;
use app\admin\model\exam\MainQuestionModel;
use app\admin\model\exam\QuestionModel;
use app\common\controller\Api;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 试题
 * @icon fa fa-circle-o
 */
class Question extends Api
{

    /**
     * QuestionModel模型对象
     * @var \app\admin\model\exam\QuestionModel
     */
    protected $model = null;
    protected $noNeedRight = ['*'];
    protected $multiFields = 'status';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\QuestionModel;
        
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $nwhere = [];
            if($this->auth->id != 1)
            {
                $nwhere['question_model.uid'] = get_admin_id($this->auth->id);
            }
            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->where($nwhere)
                ->order($sort, $order)
                ->paginate($limit);
            /*$sql = Db::getLastSql();
            echo $sql;die;*/

            foreach ($list as $row) {

                $row->getRelation('cate')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // if ($params['options_extend']) {
            //     $params['options_extend'] = json_decode(urldecode($params['options_extend']), true);
            // }
            // dd($params);
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $params['uid'] = get_admin_id($this->auth->id);
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $catelist = Db::name('exam_cate')->where(['uid'=>get_admin_id($this->auth->id),'kind'=>'QUESTION','deletetime'=>null])->select();
        $this->view->assign("cateList", $catelist);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $catelist = Db::name('exam_cate')->where(['uid'=>get_admin_id($this->auth->id),'kind'=>'QUESTION','deletetime'=>null])->select();
        $this->view->assign("cateList", $catelist);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function view($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        $this->view->assign("options_json", $options_json);
        return $this->view->fetch();
    }
    /**
     * 选项图片页面
     * @return string
     */
    public function image()
    {
        if ($this->request->isPost()) {
            $this->success($this->request->post());
        }
        return $this->view->fetch();
    }

    /**
     * 试题导入
     */
    public function importExcel()
    {
        if ($this->request->isPost()) {
            // parent::import();
            $cate = $this->request->param('cate');
            // $exam_type = $this->request->param('exam_type');
            if (!$cate) { //  || !$exam_type
                $this->error('请先选择所属类型及考试分类再进行上传');
            }
            $cname = Db::table('fa_exam_question_file')->where(['id'=>1])->value('name');

            $data = [
                'parent_id' => $cate,
                'kind' => 'QUESTION',
                'level' => 4,
                'name' => $cname,
                'uid' => get_admin_id($this->auth->id),
            ];
            $clist = Db::table('fa_exam_cate')->where($data)->find();
            if(empty($clist))
            {
                $cate = Db::table('fa_exam_cate')->insertGetId($data);
            }
            else
            {
                $cate = $clist['id'];
            }

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'csv') {
                $file     = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp       = fopen($filePath, "w");
                $n        = 0;
                while ($line = fgets($file)) {
                    $line     = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields          = [
                    'kind',
                    'title',
                    'explain',
                    'difficulty',
                    'answer',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                ];

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;

                    }
                    // $temp    = array_combine($fields, $values);
                    $row     = [];
                    $options = [];

                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];

                        if ($i > 4) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }

                    // 过滤空行
                    if (!$row['title']) {
                        continue;
                    }

                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        if ($key == 'kind') {
                            switch ($item) {
                                case '判断':
                                case '判断题':
                                    $item = 'JUDGE';
                                    break;
                                case '单选':
                                case '单选题':
                                    $item = 'SINGLE';
                                    break;
                                case '多选':
                                case '多选题':
                                    $item = 'MULTI';
                                    break;
                                case '填空':
                                case '填空题':
                                    $item = 'FILL';
                                    break;
                            }
                        } else if ($key == 'difficulty') {
                            switch ($item) {
                                case '低':
                                case '简单':
                                    $item = 'EASY';
                                    break;
                                case '高':
                                case '困难':
                                    $item = 'HARD';
                                    break;
                                default:
                                    $item = 'GENERAL';
                                    break;
                            }
                        }

                        $row[$key] = $item;
                    }

                    // 判断题特殊情况处理
                    if ($row['kind'] == 'JUDGE') {
                        switch ($row['answer']) {
                            case '正确':
                            case '对':
                                $row['answer'] = 'A';
                                break;
                            case '错误':
                            case '错':
                                $row['answer'] = 'B';
                                break;
                        }

                        $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
                    }

                    // 答案特殊处理
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace('，', ',', $row['answer']);

                    if (!$row['answer'] || ($row['kind'] == 'MULTI' && !strpos($row['answer'], ','))) {
                        throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
                    }
                    // 填空题
                    if ($row['kind'] == 'FILL') {
                        $row['answer'] = explode('|||', $row['answer']);
                        $fill_count    = count(explode('______', $row['title'])) - 1;
                        $answer_count  = count($row['answer']);

                        if ($fill_count != $answer_count) {
                            throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
                        }

                        $fill_answers = [];
                        foreach ($row['answer'] as $item) {
                            $fill_answers[] = ['answers' => explode(',', $item)];
                        }

                        $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
                    }

                    $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
                    $row['cate_id']      = $cate;
                    $row['uid']          = $this->auth->id;
                    // $row['exam_type_id'] = $exam_type;
                    $insert[] = $row;
                }

                Session::set('import_question', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            // return json($insert);
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }

    /**
     * 试题导入提交
     * @return string|void
     */
    public function import()
    {

        if ($this->request->isPost()) {

            // 加载数据
            $insert = Session::pull('import_question');
            if (!$insert) {
                $this->error(__('没有可以导入的数据，请重新上传Excel文件'));
            }

            try {
                $this->model->saveAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            $this->success();
        }

        $where = [
            'parent_id' => 0,
            'kind' => 'QUESTION',
            'uid' => get_admin_id($this->auth->id),
            'deletetime' => null
        ];
        $clist = Db::table('fa_exam_cate')->where($where)->order('sort asc')->select();

        $this->view->assign("clist", $clist);
        return $this->view->fetch();
    }
    public function get_qcate()
    {
        if ($this->request->isAjax())
        {
            $cid = $this->request->request('cid');
            $where = [
                'parent_id' => $cid,
                'uid' => get_admin_id($this->auth->id),
                'kind' => 'QUESTION',
                'deletetime' => null
            ];
            $clist = Db::table('fa_exam_cate')->where($where)->order('sort asc')->select();

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => ['list'=>$clist],
            ];
            return json($result);
        }
    }

    /**
     * 获取题库数量
     */
    public function getCount()
    {
        $cate_ids = $this->request->param('cate_ids');

        if (!$cate_ids) {
            $this->error('请先选择题库');
        }

        $this->success('', '', $this->model->getCount($cate_ids));
    }

    /**
     * 选择题目页面
     */
    public function select()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function test()
    {
        $this->success('', '', Session::get('import_question'));
    }

    /**
     * 检查答案输入
     * @param $params
     */
    protected function checkAnswer(&$params)
    {
        $answer  = $params['answer'] ?? '';
        $options = $params['options_json'] ?? [];

        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!$answer) {
                $this->error('请设置题目答案');
            }
            if (!$options) {
                $this->error('请设置题目选项');
            }

            $options     = json_decode($options, true);
            $option_keys = array_keys($options);

            // 多选题
            if (strpos($answer, ',') !== false) {
                $answer_arr = explode(',', trim($answer));
                foreach ($answer_arr as $item) {
                    if (!in_array($item, $option_keys)) {
                        $this->error('答案设置有误，答案选项不存在');
                    }
                }
            } else {
                if (!in_array($answer, $option_keys)) {
                    $this->error('答案设置有误，答案选项不存在');
                }
            }
        }

        // 后期拓展题型
        switch ($params['kind']) {
            // 填空题
            case 'FILL':
                if (!is_array($answer) || !count($answer)) {
                    $this->error('未设置填空题答案，至少设置一个');
                }

                // 扩展格式
                // $params['options_extend'] = [];
                // for ($i = 0; $i < count($params['answer']); $i++) {
                //     $params['options_extend'][] = [
                //         'user_answer' => '',
                //     ];
                // }
                // $params['options_extend'] = json_encode($params['options_extend']);

                // 转json
                $params['answer'] = json_encode($params['answer'], JSON_UNESCAPED_UNICODE);
                break;
        }
    }

    /**
     * 处理选项图片链接域名
     * @param $data
     */
    protected function optionsImage(&$data)
    {
        $options_img = $data['options_img'] ?? [];
        $options_img = json_decode($options_img, true);
        if ($options_img) {
            foreach ($options_img as &$item) {
                if (strpos($item['value'], '://') === false) {
                    $item['value'] = cdnurl($item['value'], true);
                }
            }
        }
        $data['options_img'] = json_encode($options_img);
        $data['options_img'] = $data['options_img'] == 'null' ? [] : $data['options_img'];
    }

    /**
     * 检查题目内容输入
     * @param $params
     */
    protected function checkTitle(&$params)
    {
        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!($params['title'] ?? '')) {
                $this->error('请输入题目内容');
            }
        } else if ($params['kind'] == 'FILL') {
            if (!($params['title_fill'] ?? '')) {
                $this->error('请输入填空题题目内容');
            }
            $params['title'] = $params['title_fill'];
        }
    }
    /**
     * 试题分配
     * auth:zlq
     * data:2023.09.07
     * sql:INSERT INTO `xdzs_tswm_club`.`fa_auth_rule`(`id`, `type`, `pid`, `name`, `title`, `icon`, `url`, `condition`, `remark`, `ismenu`, `menutype`, `extend`, `py`, `pinyin`, `createtime`, `updatetime`, `weigh`, `status`) VALUES (NULL, 'file', 85, 'exam/question/allocation', '试题分配', 'fa fa-question-circle-o', '', '', '', 1, NULL, '', 'stfp', 'shitifenpei', 1694075580, 1694075580, 0, 'normal')
     * ALTER TABLE `xdzs_tswm_club`.`fa_exam_question`
    ADD COLUMN `describe` text NULL COMMENT '简介' AFTER `admin_id`;
     */
    public function allocation()
    {
        $where = [
            'status' => 1,
        ];
        $db2 = Db::connect('db2');
        $tiku_id = $this->auth->tiku_id;
        $list = [];
        if(!empty($tiku_id))
        {
            $where['id'] = ['in',$tiku_id];
            $admin_id = get_admin_id($this->auth->id);
            $num = Db::name('admin')->where('id', $admin_id)->value('num');
            $defaultId = $db2->name('exam_cate')->where('is_default', 'YES')->value('id');
            $list = $db2->table('fa_classes_tiku')->where($where)->whereOr('cate_id','=', $defaultId)->order('id asc');
            if ($num) $list = $list->limit($num+1);

            $list = $list->select();

        }
//        dump($list);die;
        $tkwhere = [
            'deletetime' => null,
            'level' => 1,
            'kind' => 'QUESTION',
            'uid' => $this->auth->id,
        ];
        $tklist = Db::name('exam_cate')->where($tkwhere)->order('id asc')->select();

        $this->assign('list', $list);
        $this->assign('tklist', $tklist);

        return $this->view->fetch();
    }
    public function allocation_s()
    {
        $where = [
            'kind' => 'QUESTION',
            'level' => 1,
            'deletetime' => null,
            'uid' => get_admin_id($this->auth->id),
        ];
        $list = Db::name('exam_cate')->where($where)->order('sort asc')->select();

        $tkwhere = [
            'uid' => get_admin_id($this->auth->id)
        ];
        $auth = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
        if($auth['group_id'] == 3)
        {
            $teacher = Db::name('classes_teacher')->where('user_id',$this->auth->id)->find();
            $tkwhere['profile_id'] = $teacher['profile_id'];
        }
        $tklist = Db::name('classes_class')->where($tkwhere)->order('id desc')->select();

        $this->assign('list', $list);
        $this->assign('tklist', $tklist);

        return $this->view->fetch();
    }
    public function get_classlist()
    {
        if ($this->request->isAjax())
        {
            $tkwhere = [
                'uid' => get_admin_id($this->auth->id)
            ];

            $auth = Db::name('auth_group_access')->where('uid', $this->auth->id)->find();
            if ($auth['group_id'] == 3) {
                $teacher = Db::name('classes_teacher')->where('user_id', $this->auth->id)->find();
                $tkwhere['profile_id'] = $teacher['profile_id'];
            }
            $tklist = Db::name('classes_class')->where($tkwhere)->field('title as name,id as value')->order('id desc')->select();

            return json($tklist);
        }
    }
    /**
     * 获取试题列表
     * auth:zlq
     * data:2023.09.08
     */
    public function get_question()
    {


            $cid = $this->request->request('cid');
            $where = [
                'cate_id' => $cid,
                'deletetime' => null
            ];
            $list = Db::table('fa_exam_question')->field('id')->where($where)->order('id asc')->select();

            if (!empty($list))
            {
                $number = count($list);
                $cwhere = [ 'id' => $cid ];
                $clist = Db::table('fa_exam_cate')->field('name')->where($cwhere)->find();
                foreach ($list as $k => $v)
                {
                    $num = $k+1;
                    if($num < 10)
                    {
                        $num = '0'.$num;
                    }
//                    $list[$k]['name'] = $clist['name'] . ' - ' . $num;
                    $list[$k]['name'] = $clist['name'] . ' - ' . $v['id'];
                }
                $where1 = [
                    'parent_id' => $cid,
                    'kind' => 'QUESTION',
                    'deletetime' => null
                ];
                $clist1 = Db::table('fa_exam_cate')->where($where1)->order('sort asc')->select();
                if(!empty($clist1))
                {
                    $list1 = $clist1;
                }
                else
                {
                    $list1 = [];
                }

                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => $list,
                    'num' => $number,
                    'list' => $list1
                ];
            }
            else
            {
                $where1 = [
                    'parent_id' => $cid,
                    'kind' => 'QUESTION',
                    'deletetime' => null
                ];
                $clist1 = Db::table('fa_exam_cate')->where($where1)->order('sort asc')->select();
                if(!empty($clist1))
                {
                    $list1 = $clist1;
                }
                else
                {
                    $list1 = [];
                }
                $result = [
                    'msg' => 'success',
                    'code' => 101,
                    'data' => $list,
                    'num' => 0,
                    'list' => $list1
                ];
            }

            return json($result);

    }
    
    /**
     * 获取单个试题
     * auth:zlq
     * data:2023.09.08
     */
    public function get_view()
    {

            $qid = $this->request->request('qid');

            $row = $this->model->get($qid);

//            if (!$row) {
//                $this->error(__('No Results were found'));
//            }
//            $adminIds = $this->getDataLimitAdminIds();
//            if (is_array($adminIds)) {
//                if (!in_array($row[$this->dataLimitField], $adminIds)) {
//                    $this->error(__('You have no permission'));
//                }
//            }
            $data = array();
            switch ($row['kind']) {
                case 'SINGLE':
                    $data['kind'] = '单选题';
                    break;
                case 'JUDGE':
                    $data['kind'] = '判断题';
                    break;
                case 'MULTI':
                    $data['kind'] = '多选题';
                    break;
                case 'FILL':
                    $data['kind'] = '填空题';
                    break;
                default:
                    $data['kind'] = '单选题';
            }
            switch ($row['difficulty']) {
                case 'EASY':
                    $data['difficulty'] = '简单';
                    break;
                case 'GENERAL':
                    $data['difficulty'] = '普通';
                    break;
                case 'MULTI':
                    $data['HARD'] = '困难';
                    break;
                default:
                    $data['difficulty'] = '单选题';
            }
            $data['describe'] = $row['describe'];
            $data['title'] = $row['title'];
            $data['answer'] = $row['answer'];
            $data['id'] = $row['id'];
            $data['other_url'] = $row['other_url'];
            $data['other_name'] = $row['other_name'];

            $options_json = json_decode($row['options_json'], true);
            $data['options_json'] = $options_json;

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $data,
            ];
            return json($result);

    }
    /**
     * iframe加载
     * auth:zlq
     * data:2023.09.08
     */
    public function get_views($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        // dump($options_json);exit;
        $this->view->assign("options_json", $options_json);
        return $this->view->fetch();
    }
    /**
     * 分配题库
     * auth:zlq
     * data:2023.09.08
     */
    public function fptk()
    {
        if ($this->request->isAjax())
        {
            $ids = $this->request->request('ids');
            $describe = $this->request->request('describe');
            $tkid = $this->request->request('tkid');
            $other_url = $this->request->request('other_url');
            $other_name = $this->request->request('other_name');

            $id_arr = explode(',',$ids);

            $json_arr = array();

            $tklist = Db::table('fa_classes_tiku')->where(['id'=>$tkid])->find();
            $questions = $tklist['questions'];

            if(!empty($questions))
            {
                $questions_arr = json_decode($questions,true);

                foreach ($questions_arr as $kk => $vv)
                {
                    if(!in_array($vv['id'],$id_arr))
                    {
                        $id_arr[] = $vv['id'];
                    }
                }
            }

            foreach ($id_arr as $k => $v)
            {
                if (empty($v))
                {
                    unset($id_arr[$k]);
                }
                else
                {
                    $json_arr[$k]['id'] = $v;
                    $json_arr[$k]['score'] = 1;
                }

            }

            $json_arr = json_encode($json_arr);

            Db::table('fa_exam_question')->where('id','in',$ids)->update(['describe'=>$describe,'other_url'=>$other_url,'other_name'=>$other_name]);

            Db::table('fa_classes_tiku')->where(['id'=>$tkid])->update(['questions'=>$json_arr]);

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
    //生成试卷
    public function scsj()
    {
        if ($this->request->isAjax())
        {
            $question_ids = $this->request->request('question_ids');
            $describe = $this->request->request('describe');
            $title = $this->request->request('title');
            $question_ids = trim($question_ids,',');
//            dump($question_ids);die;
            $list = Db::name('exam_papers')->where(['title'=>$title,'deletetime'=>null])->find();
            if(!empty($list))
            {
                $result = [
                    'msg' => 'success',
                    'code' => 101,
                    'data' => [],
                ];
                return json($result);
            }

            Db::startTrans();
            try {

                $data = [
                    'title' => $title,
                    'describe' => $describe,
                    'question_ids' => $question_ids,
                    'createtime' => time(),
                    'uid' => get_admin_id($this->auth->id),
                ];
                if(get_auth_group($this->auth->id) == 3)
                {
                    $profile_id = get_profile_id($this->auth->id);
                    $data['profile_id'] = $profile_id;
                    $data['share_ids'] = $profile_id;
                }
                else
                {
                    $data['profile_id'] = 0;
                    $data['share_ids'] = 0;
                }

                Db::name('exam_papers')->insert($data);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
    /**
     * 删除
     * auth:zlq
     * data:2023.09.14
     */
    public function qdel()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('del_id');
            $list = Db::table('fa_exam_question')->where('id', $qid)->find();
            if (!empty($list))
            {
                Db::table('fa_exam_question')->where('id', $qid)->update(['deletetime' => time()]);
                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => ['cate_id' => $list['cate_id']],
                ];
                return json($result);
            }
        }
    }
    /**
     * 随机分配
     * auth:zlq
     * data:2023.09.14
     */
    public function sjfp()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('qid');
            $tkid = $this->request->request('tkid');
            $shu_num = $this->request->request('shu_num');
            $describe = $this->request->request('describe');
            $other_url = $this->request->request('other_url');

            $qlist = Db::table('fa_exam_question')->where('id', $qid)->find();

            $where = [
                'cate_id' => $qlist['cate_id'],
                'deletetime' => null
            ];
            $count = Db::table('fa_exam_question')->where($where)->count();

            if ($shu_num == 0)
            {
                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => [],
                ];
                return json($result);
            }
            elseif ($shu_num >= $count)
            {
                $list = Db::table('fa_exam_question')->where($where)->select();
            }
            elseif ($shu_num < $count)
            {
                $list = Db::table('fa_exam_question')->where($where)->orderRaw("RAND()")->limit($shu_num)->select();
            }

            $json_arr = array();
            $ids = '';
            foreach ($list as $k => $v)
            {
                $json_arr[$k]['id'] = $v['id'];
                $json_arr[$k]['score'] = 1;
                $ids .= $v['id'] . ',';
            }
            $ids = trim($ids,',');
            $json_arr = json_encode($json_arr);

            Db::table('fa_exam_question')->where('id', 'in', $ids)->update(['describe' => $describe,'other_url'=>$other_url]);

            Db::table('fa_classes_tiku')->where(['id' => $tkid])->update(['questions' => $json_arr]);

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
    public function get_cate_this()
    {
        if ($this->request->isAjax())
        {
            $cid = $this->request->request('cid');
            $where = [
                'parent_id' => $cid,
                'deletetime' => null
            ];
            $list = Db::name('exam_cate')->field('id,name')->where($where)->order('id asc')->select();

            $result = [
                'msg' => 'success',
                'code' => 1,
                'data' => $list,
            ];

            return json($result);
        }
    }

    public function get_cate_one()
    {
        if ($this->request->isAjax())
        {
            $cid = $this->request->request('cid');
            $where = [
                'parent_id' => $cid,
                'deletetime' => null
            ];
            $db2 = Db::connect('db2');
            $list = $db2->name('exam_cate')->field('id,name')->where($where)->order('id asc')->select();
//            dump($list);die;
            $result = [
                'msg' => 'success',
                'code' => 1,
                'data' => $list,
            ];

            return json($result);
        }
    }

    /**
     * 查询第四级题库对应下的所有试题
     * @param int $cid 分类id
     */
    public function get_question_new()
    {
        $cid = $this->request->request('cid');
        //查询级分类对应的试题集合
        $questionList = MainQuestionModel::getQuestionByCateId($cid);
        $result = [
            'msg' => 'success',
            'code' => 100,
            'data' => $questionList,
            'num' => count($questionList),
        ];

        return json($result);
    }

    /**
     * 历史编写get_question_new备份
     */
    // public function get_question_new()
    // {
    //     if ($this->request->isAjax())
    //     {
    //         $db2 = Db::connect('db2');
    //         $cid = $this->request->request('cid');
    //         $where = [
    //             'cate_id' => $cid,
    //             'deletetime' => null
    //         ];
    //         $list = $db2->table('fa_exam_question')->field('id')->where($where)->order('id asc')->select();

    //         if (!empty($list))
    //         {
    //             $number = count($list);
    //             $cwhere = [ 'id' => $cid ];
            
    //             $clist = $db2->table('fa_exam_cate')->field('name')->where($cwhere)->find();
    //             foreach ($list as $k => $v)
    //             {
    //                 $num = $k+1;
    //                 if($num < 10)
    //                 {
    //                     $num = '0'.$num;
    //                 }
    //                 $list[$k]['name'] = $clist['name'] . ' - ' . $num;
    //             }
    //             $where1 = [
    //                 'parent_id' => $cid,
    //                 'kind' => 'QUESTION',
    //                 'deletetime' => null
    //             ];
    //             $clist1 = $db2->table('fa_exam_cate')->where($where1)->order('sort asc')->select();
    //             if(!empty($clist1))
    //             {
    //                 $list1 = $clist1;
    //             }
    //             else
    //             {
    //                 $list1 = [];
    //             }

    //             $result = [
    //                 'msg' => 'success',
    //                 'code' => 100,
    //                 'data' => $list,
    //                 'num' => $number,
    //                 'list' => $list1
    //             ];
    //         }
    //         else
    //         {
    //             $where1 = [
    //                 'parent_id' => $cid,
    //                 'kind' => 'QUESTION',
    //                 'deletetime' => null
    //             ];
    //             $clist1 = $db2->table('fa_exam_cate')->where($where1)->order('sort asc')->select();
    //             if(!empty($clist1))
    //             {
    //                 $list1 = $clist1;
    //             }
    //             else
    //             {
    //                 $list1 = [];
    //             }
    //             $result = [
    //                 'msg' => 'success',
    //                 'code' => 101,
    //                 'data' => $list,
    //                 'num' => 0,
    //                 'list' => $list1
    //             ];
    //         }

    //         return json($result);
    //     }
    // }

    public function get_view_new()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('qid');
            $db2 = Db::connect('db2');
            $row = $db2->name('exam_question')->find($qid);

            if (!$row) {
                $this->error(__('No Results were found'));
            }

            $data = array();
            switch ($row['kind']) {
                case 'SINGLE':
                    $data['kind'] = '单选题';
                    break;
                case 'JUDGE':
                    $data['kind'] = '判断题';
                    break;
                case 'MULTI':
                    $data['kind'] = '多选题';
                    break;
                case 'FILL':
                    $data['kind'] = '填空题';
                    break;
                default:
                    $data['kind'] = '单选题';
            }
            switch ($row['difficulty']) {
                case 'EASY':
                    $data['difficulty'] = '简单';
                    break;
                case 'GENERAL':
                    $data['difficulty'] = '普通';
                    break;
                case 'MULTI':
                    $data['HARD'] = '困难';
                    break;
                default:
                    $data['difficulty'] = '单选题';
            }
            $data['describe'] = $row['describe'];
            $data['title'] = $row['title'];
            $data['answer'] = $row['answer'];
            $data['id'] = $row['id'];
            $data['other_url'] = $row['other_url'];
            $data['other_url2'] = $row['other_url2'];
            $data['other_url3'] = $row['other_url3'];
            $data['other_name'] = $row['other_name'];

            $options_json = json_decode($row['options_json'], true);
            $data['options_json'] = $options_json;

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $data,
            ];
            return json($result);
        }
    }
    /**
     * iframe加载
     * auth:zlq
     * data:2023.09.08
     */
    public function get_views_new($ids = null)
    {
        $db2 = Db::connect('db2');
        $row = $db2->name('exam_question')->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        // dump($options_json);exit;
        $this->view->assign("options_json", $options_json);
        return $this->view->fetch();
    }

    public function fptk_new()
    {
        if ($this->request->isAjax())
        {
            $ids = $this->request->request('ids');
            $tkid = $this->request->request('tkid');
//            $count = $this->request->request('count');

            // $ids = trim($ids,',');
            $ids = json_decode($ids, 256);
            $ids = array_column($ids, 'id', 'sort');
            ksort($ids);
            /*$id_arr = explode(',',$ids);
            unset($id_arr[0]);
            unset($id_arr[1]);
            unset($id_arr[2]);
            unset($id_arr[3]);
            unset($id_arr[4]);
            $arr_count = count($id_arr);
            $ids = implode($id_arr,',');*/


            Db::startTrans();
            try{
                if ($ids) {
                    Db::startTrans();
                    $saveData = [];
                    $msg = '';
                    $questionModel = new QuestionModel;
                    $db2 = Db::connect('db2')->name('exam_question');
                    foreach ($ids as $v) {
                        $list = $db2->where(['cate_id'=>$v])->select();

                        if ($list) {
                            foreach ($list as $items) {
                                unset($items['id']);
                                $items['cate_id'] = $tkid;
                                $items['createtime'] = time();
                                $items['updatetime'] = time();
                                $items['uid'] = $this->auth->id;
                                $saveData[] = $items;
                                if (count($saveData) == 500) {
                                    //插入数据
                                    $res = $questionModel->saveAll($saveData);
                                    if (!$res) {
                                        Db::rollback();
                                        $msg = '数据生成失败';
                                        break;
                                    }
                                    unset($saveData);
                                }
                            }
                        }
                    }
                    if (count($saveData)>0) {
                        //插入数据
                        $res = $questionModel->saveAll($saveData);
                        if (!$res) {
                            Db::rollback();
                            $msg = '数据生成失败';
                        }
                    }
                }

                if ($msg) {
                    return json([
                        'msg' => '数据生成失败',
                        'code' => 400,
                        'data' => [],
                    ]);
                } 
                //不知道啥原因，需要两次commit才能提交成功
                Db::commit();
                Db::commit();


                $result = [
                    'msg' => 'success',
                    'code' => 1,
                    'data' => [],
                ];
                return json($result);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $e->getMessage().'line:'.$e->getLine();
            }
        }
    }
    //获取单个题
    public function getOne()
    {
        if ($this->request->isAjax())
        {
            $id = $this->request->request('id');
            $list = Db::name('exam_question')->find($id);
            $cwhere = [ 'id' => $list['cate_id'] ];
            $clist = Db::name('exam_cate')->field('name')->where($cwhere)->find();

            $list['name'] = $clist['name'] . ' - ' . $list['id'];

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $list,
            ];
            return json($result);
        }
    }
    //编辑
    public function papers_edit($ids = null)
    {

        $where = [
            'kind' => 'QUESTION',
            'level' => 1,
            'deletetime' => null,
            'uid' => get_admin_id($this->auth->id),
        ];
        $list = Db::name('exam_cate')->where($where)->order('sort asc')->select();

        $papers = Db::name('exam_papers')->find($ids);

        $this->view->assign('list', $list);
        $this->view->assign('papers', $papers);

        return $this->view->fetch();
    }
    //papers全部
    public function getAll()
    {
        if ($this->request->isAjax())
        {
            $papers_id = $this->request->request('papers_id');

            $papers = Db::name('exam_papers')->find($papers_id);
            $where['id'] = ['in',$papers['question_ids']];
            $list = Db::name('exam_question')->where($where)->order('id asc')->select();

            if (!empty($list))
            {
                foreach ($list as $k => $v)
                {
                    $cwhere = ['id' => $v['cate_id']];
                    $clist = Db::name('exam_cate')->field('name')->where($cwhere)->find();
                    $list[$k]['name'] = $clist['name'] . ' - ' . $v['id'];
                }
            }
            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $list,
            ];
            return json($result);
        }
    }
    //修改试卷
    public function xgsj()
    {
        if ($this->request->isAjax())
        {
            $question_ids = $this->request->request('question_ids');
            $describe = $this->request->request('describe');
            $title = $this->request->request('title');
            $papers_id = $this->request->request('papers_id');
            $question_ids = trim($question_ids,',');

            Db::startTrans();
            try {

                $data = [
                    'title' => $title,
                    'describe' => $describe,
                    'question_ids' => $question_ids,
                ];

                Db::name('exam_papers')->where(['id'=>$papers_id])->update($data);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
}
